package com.tool_stdy.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Calendar;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientUtil extends PostMethod {
    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
    private HttpClientUtil() {
    }

    private static final class HttpClientHandler {
       private static HttpClientUtil client = new HttpClientUtil();
    }

    public static HttpClientUtil getInstance() {
        return HttpClientHandler.client;
    }

    public static void main(String[] args) {
        /*
         * String result = HttpClientUtil .getInstance() .getData(
         * "http://10.10.34.109:8080/ott-api-hubo-web/getStreamByDate.json",
         * "beginTime=2014-04-20&endTime=2014-04-21", 3000); ResContent
         * resultMap = JSON.parseObject(result, ResContent.class);
         * 
         * HashMap dataMap = JSON.parseObject(resultMap.getData().toString(),
         * HashMap.class); List<Stream> list =
         * JSON.parseArray(dataMap.get("streamList") + "", Stream.class);
         */
        /*
         * int i = 1100;
         * 
         * System.out.println(i / 1000.0);
         * 
         * List<VideoSplit> list = new ArrayList<VideoSplit>(); String result =
         * HttpClientUtil .getInstance() .getData(
         * "http://127.0.0.1:8080/ott-live-web/live.action",
         * "streamName=dian&main=true", 3000); if
         * (StringUtils.isNotEmpty(result)) { ResContent resultMap =
         * JSON.parseObject(result, ResContent.class); if
         * ("200".equals(resultMap.getStatus())) { HashMap dataMap =
         * JSON.parseObject(resultMap.getData() .toString(), HashMap.class);
         * list = JSON.parseArray(dataMap.get("clipList") + "",
         * VideoSplit.class);
         * 
         * 
         * } }
         */

        /*for (int i = 0; i < 1000; i++) {
        	String result = HttpClientUtil.getInstance().getData(
        			"http://127.0.0.1:8080/ott-live-web/live.action",
        			"streamName=" + "dianying_h" + "&main=true", 3000);
        }*/

        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        Integer s = Integer.parseInt(cal.getTimeInMillis() / 1000 + "");
        System.out.println(s);
        System.out.println(Integer.MAX_VALUE);
    }

    /**
     * 模拟get请求
     * 
     * @param url
     * @param param
     * @param time
     * @return
     */
    public static String getData(String url, String param, int time) {
        String result = "";
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setContentCharset("UTF-8");
        String urlNameString = url + "?" + param;
        GetMethod getMethod = new GetMethod(urlNameString);
        try {

            HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();

            // 设置连接超时时间(单位毫秒)
            managerParams.setConnectionTimeout(time);
            // 设置请求超时时间
            managerParams.setSoTimeout(time);

            // 设置请求重试
            managerParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

            // 执行getMethod
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode != HttpStatus.SC_OK) {
                logger.error(" Method failed:  url==" + urlNameString + "  " + getMethod.getStatusLine());
            }
            // 读取内容
            byte[] responseBody = getMethod.getResponseBody();
            // 处理内容
            result = new String(responseBody);
        } catch (Exception e) {
            // 发生致命的异常，可能是协议不对或者返回的内容有问题
            logger.error("Please check your provided http address! url==" + urlNameString, e);

        }
        //		catch (IOException e) {
        //			logger.error("HttpClientUtil.getData IOException", e);
        //		} 
        finally {
            // 释放连接
            getMethod.releaseConnection();
            httpClient.getHttpConnectionManager().closeIdleConnections(0);
            return result;
        }
    }

    /**
     * 模拟提交表单请求
     * 
     * @param url
     * @param data
     * @return
     */
    public static String postDataToUri(String url, NameValuePair[] data, int time) {
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setContentCharset("UTF-8");
        PostMethod post = new PostMethod(url);
        post.setRequestBody(data);

        HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();

        // 设置连接超时时间(单位毫秒)
        managerParams.setConnectionTimeout(time);
        // 设置请求超时时间
        managerParams.setSoTimeout(time);
        // 设置请求重试
        managerParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        post.addRequestHeader("Authorization", "jditemservice");
        try {
            int statusCode = httpClient.executeMethod(post);
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("Post Data Failure: " + post.getStatusLine());
                return "ERROR";
            }
            InputStream inputStream = post.getResponseBodyAsStream();
            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = bufferReader.readLine()) != null) {
                sb.append(line);
            }
            bufferReader.close();
            return sb.toString();
        } catch (Exception ex) {
            logger.error("postDataToUri ERROR.", ex);
            return "ERROR";
        } finally {
            // 释放链接
            post.releaseConnection();
            httpClient.getHttpConnectionManager().closeIdleConnections(0);
        }
    }

    /**
     * 模拟POST方式获取数据
     * 
     * @param url
     *            请求URL
     * @param params
     *            请求参数
     * @param content
     *            请求参数值
     * @param charset
     *            字符集
     * @return
     */
    public String post(String url, String params, String content, String charset, Integer timeOut) {

        // 响应内容
        String result = "";

        HttpClient httpClient = new HttpClient();
        HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();

        // 设置连接超时时间(单位毫秒)
        managerParams.setConnectionTimeout(timeOut);

        // 设置请求超时时间
        managerParams.setSoTimeout(timeOut);

        PostMethod postMethod = new PostMethod(url);

        try {

            // 设置http的请求头
            postMethod.addRequestHeader("Authorization", "jditemservice");
            postMethod.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=" + charset);
            postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset);

            // 填入各个表单域的值
            NameValuePair[] data = { new NameValuePair(params, content) };

            // 将表单的值放入postMethod中
            postMethod.setRequestBody(data);

            // 定义访问地址的链接状态
            int statusCode = 0;

            try {
                // 客户端请求url数据
                statusCode = httpClient.executeMethod(postMethod);
            } catch (Exception e) {
                logger.error("deliverBrandService statusCode error", e);
            }

            // 请求成功状态-200
            if (statusCode == HttpStatus.SC_OK) {
                try {
                    result = postMethod.getResponseBodyAsString();
                } catch (IOException e) {
                    logger.error("deliverBrandService result error", e);
                }
            } else {
                logger.error("请求返回状态：" + statusCode);
            }

        } catch (Exception e) {
            logger.error("deliverBrandService post error", e);
        } finally {

            // 释放链接
            postMethod.releaseConnection();
            httpClient.getHttpConnectionManager().closeIdleConnections(0);
        }

        return result;
    }

}
